<?php
namespace application\datatypes;

class Url extends DataType {
	public static $name = 'Url';
	public static $fields = array(array('columnType'=>'VARCHAR(200)'));
	
	public static function validate($field, $data, $results) {
		$pattern = "<((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)>";
		if($field->cf_required && !$data[$field->cf_column]) {
			$results['errors'][] = $field->cf_display_name.' is required';
		}
		elseif(preg_match($pattern, $data[$field->cf_column])) {
			/** Valid URL, and we post it */
			$results['db_fields'][$field->cf_column] = $_REQUEST[$field->cf_column];
		}
		elseif(preg_match($pattern, 'http://'.$data[$field->cf_column])) {
			$results['db_fields'][$field->cf_column] = 'http://'.$data[$field->cf_column];
		}
		elseif($data[$field->cf_column]) {
			$results['errors'][] = $field->cf_display_name.' must be a valid URL.';
		}		
		return $results;
	}
	
	public static function display($formElements) {
		?>
		
		<fieldset class="single-field">
			<header><?=$formElements['display']?></header>
			<section class="inner">
			<?php if($description = $formElements['description']) : ?>
				<p class="form-description"><?=$description?></p>
			<?php endif;?>
			<?=$formElements['elements']['element']?>
			</section>
		</fieldset>
		<?php
	}
	
	public static function build($field, $data) {
		$value = $data[$field->cf_column];
		$formElements = array('description'=>$field->cf_description, 'column'=>$field->cf_column, 'display'=>$field->cf_display_name, 'data_type'=>$field->cf_data_type, 'elements'=>array(
				'element'=>
					sprintf('<input type="text" value="%1$s" class="long-text url-mask" name="%2$s" id="%2$s"/>', $value, $field->cf_column)
				
				));
		return $formElements;
	
	}
	
}
?>